/*
Copyright 2021 LuJun

Permission is hereby granted, free of charge, to any person obtaining a copy 
of this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights 
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
copies of the Software, and to permit persons to whom the Software is furnished 
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in 
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

import { error, __private, Asset } from 'cc';
import { GetPackRefKey, PackLoaderBase } from './pack-loader-base';
import {
    reference,
    asset,
    path,
    request,
    RequestOptions,
    assetLoader,
    event,
    EVENT_PACK_LOADING,
    EVENT_PACK_LOADED,
    asyncIO
} from '../core';

const TAG = 'lcc/pack/pack-manager.ts';

/**
 * @zh
 * 包管理器
 */
class PackManager {
    /**
     * @zh
     * 单例对象
     */
    private static _instance: PackManager = null!;

    /**
     * @zh
     * 获得单例对象
     */
    static get instance() {
        if (PackManager._instance === null) {
            PackManager._instance = new PackManager();
        }
        return PackManager._instance;
    }

    /**
     * @zh
     * 包映射表
     */
    private _packMap: { [key: string]: PackLoaderBase } = Object.create(null);

    /**
     * @zh
     * 构造函数
     */
    private constructor() {}

    /**
     * @zh
     * 获得指定包
     *
     * @param packName - 包名称
     */
    getPack<T extends PackLoaderBase>(packName: string) {
        return this._packMap[packName] as T;
    }

    /**
     * @zh
     * 释放未使用的包资源
     *
     * @param packName 包名称
     */
    releaseUnusedAssets(packName: string) {
        let pack = this._packMap[packName];
        if (pack) {
            pack.releaseUnusedAssets();
        }
    }

    /**
     * @zh
     * 加载包
     *
     * @param nameOrUrl - 包名称或者URL路径
     */
    async loadPack(
        nameOrUrl: string,
        options: __private._cocos_core_asset_manager_shared__IBundleOptions | null = null
    ) {
        let packName = path.basename(nameOrUrl);
        let pack = this._packMap[packName];
        if (!pack) {
            let bundle = await asset.loadBundle(nameOrUrl, options);
            let PackLoaderType =
                reference.get<typeof PackLoaderBase>(GetPackRefKey(packName, 'PackLoader')) || PackLoaderBase;
            pack = new PackLoaderType(packName, bundle);
            this._packMap[packName] = pack;

            try {
                event.emit(EVENT_PACK_LOADING + packName);
                event.emit(EVENT_PACK_LOADING, packName);

                // 等待异步IO结束，执行包加载函数
                await asyncIO.complete();
                pack.onLoad();

                event.emit(EVENT_PACK_LOADED + packName);
                event.emit(EVENT_PACK_LOADED, packName);
            } catch (e) {
                error(TAG, `loadPack Exception ${e}`);
            }
        }
        return pack;
    }

    /**
     * @zh
     * 加载包内资源
     *
     * @param packName - 包名称
     * @param path - 资源路径
     * @param type - 资源类型
     */
    loadAsset<T extends Asset>(
        packName: string,
        path: string,
        type: __private._cocos_core_asset_manager_shared__AssetType<T>
    ) {
        let pack = packMgr.getPack(packName);
        if (!pack) {
            error(TAG, `pack ${packName} not found`);
            return null;
        }

        return pack.loadAsset<T>(path, type);
    }
}

/**
 * @zh
 * 包管理器对象
 */
export const packMgr = PackManager.instance;

/**
 * @zh
 * 拆分包路径
 *
 * @param packPath 包路径
 *
 * @returns [包名称,路径]
 */
export function SplitPackPath(packPath: string) {
    let spos = packPath.indexOf('/');
    return [packPath.substring(0, spos), packPath.substring(spos + 1)];
}

/**
 * @zh
 * 注册 asset 协议，用于从包加载资源
 */
request.register('asset', {
    async get(mainproto: string, subproto: string, path_: string, options?: RequestOptions) {
        // 解析路径
        let [packPath, extname] = path.splitext(path_);

        // 资源类型为子协议或者后缀名
        let assetType = subproto || extname;
        if (!assetType) {
            error(TAG, `asset '${path_}' type unknown`);
            return null;
        }
        assetType = assetType.toLowerCase();

        // 解析包路径
        let [packName, assetPath] = SplitPackPath(packPath);

        let pack = packMgr.getPack(packName);
        if (!pack) {
            error(TAG, `pack ${packName} not found`);
            return null;
        }

        return assetLoader.load(assetType, assetPath, pack.bundle);
    }
});
